package com.veetao.api.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import com.veetao.api.dao.SysConfigDAO;
import com.veetao.api.model.ConfigChangeListener;
import com.veetao.api.model.SystemConfig;

/**
 * 
 * @author guohongtao
 * @date 2016年8月26日
 */
@Service
public class SystemConfigService implements InitializingBean {
	
	public static final String CONFIG_SWITCH_ON = "on";
	public static final String CONFIG_SWITCH_OFF = "off";
	
	public static final String IOS_SWITCHER = "ios_switcher";
	public static final String WEIXIN_PUBLIC_APP_ID = "wx_public_appid";
	public static final String WEIXIN_PUBLIC_APP_SECRET = "wx_public_appsecret";
	public static final String USER_FEED_MAX_CACHE_SIZE = "user_feed_max_cache_size";
	public static final String USER_FEED_MAX_RELATED_FEED_SIZE = "user_feed_max_related_size";
	public static final String REC_FEED_ORDER = "rec_feed_order";
	public static final String ALLOW_AD_APPS = "allow_ad_apps";
	
	public static String FEED_HOME_TEST_UIDS  = "feed_home_test_uids";
	
	@Resource
	private SysConfigDAO dao;
	Map<String,String> configContainer;
	@Resource
	private List<ConfigChangeListener> configChangeListeners;

	/**
	 * @param iosSwitcher
	 * @return
	 * @author guohongtao
	 */
	public String getConfig(String configName) {
		return configContainer.get(configName);
	}

	public void reloadConfigs() {
		List<SystemConfig> configs = dao.queryAllSystemConfig();
		
		Map<String,String> configMap = new HashMap<String, String>();
		for(SystemConfig c : configs) {
			configMap.put(c.getName(), c.getValue());
		}
		
		this.configContainer = configMap;
		
    	if(configChangeListeners != null) {
    		for(ConfigChangeListener l : configChangeListeners) {
    			l.onConfigChange(this);
    		}
    	}
		
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		reloadConfigs();
	}

	public List<ConfigChangeListener> getConfigChangeListeners() {
		return configChangeListeners;
	}

	public void setConfigChangeListeners(
			List<ConfigChangeListener> configChangeListeners) {
		this.configChangeListeners = configChangeListeners;
	}
	

}
